import baseConfig from './config.js'

import {
	getToken,
	logout,
	getDomains
} from './comm.js'
module.exports = (vm) => {
	uni.$u.http.setConfig((config) => {
		config.baseURL = baseConfig.baseURL;
		return config
	})

	uni.$u.http.interceptors.request.use((config) => {
		config.dataType = 'json'
		config.timeout = 120000
		config.data = config.data || {}
		config.header['content-type'] = 'application/x-www-form-urlencoded'
		config.header.Token = getToken()
		config.header.Domains = getDomains()
		console.log('config', config)
		return config
	}, config => {
		return Promise.reject(config)
	})

	// 响应拦截
	uni.$u.http.interceptors.response.use((response) => {
		const data = response.data
		let domains = getDomains()
		console.log('res', response)
		if (data.code === -1) {
			//登录
			logout()
			
			uni.showModal({
				title: '去登录',
				content: data.msg,
				success: function(res) {
					if (res.confirm) {
						if (domains == 'Mini') {
							
						} else {
							uni.navigateTo({
								url: 'pages/login/index/index'
							})
						}
					} else if (res.cancel) {
						if (domains == 'Mini') {
							
						} else {
							uni.webView.switchTab({
								url: '/pages/index/index'
							})
						}
					}
				}
			})
			return new Promise(() => {})
		}
		if (data.code === 1) {
			uni.$u.toast(data.msg)
			return Promise.reject(data)
		}
		return data
	}, (response) => {
		if (response.statusCode) {
			if (response.statusCode === 404) {
				uni.$u.toast('404 Not Found')
			}
		} else {
			uni.$u.toast('网络请求失败')
		}

		return Promise.reject({
			response
		})
	})
}
